#include "page0.h"          // 我的设备
#include "ui_page0.h"
#include<QDebug>
#include<QFileDialog>
#include<QHeaderView>
#include<QJsonParseError>
#include<QJsonArray>
#include<QTreeWidgetItem>
#include<QTreeWidgetItemIterator>
#include<QRegExp>
#include<QMessageBox>
#include"src/mes.h"
#include"src/rdesktoptip.h"
#include<QMenu>
#include"saveqrcode.h"
#include<QClipboard>
#include"repairdialog.h"
#include"repairhistorydialog.h"
#include"checkhistorydialog.h"


Page0::Page0(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page0)
{
    ui->setupUi(this);
    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    popMenu->addAction("报修申请",this,SLOT(slot_repairApply()));
    popMenu->addAction("点检历史查询",this,SLOT(slot_checkHistoryQuery()));
    popMenu->addAction("维修历史查询",this,SLOT(slot_repairHistoryQuery()));
    popMenu->addAction("生成二维码",this,SLOT(slot_createQRcode()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));

    ui->userWorkNumber->addItem(Mes::getInstance()->name);
    initTableView(QStringList());
    initTabText();

    refreshTimer->start(1000*3600*4);       //  消息提醒周期 4h
    connect(refreshTimer,SIGNAL(timeout()),this,SLOT(initTabText()));
}

void Page0::slot_checkHistoryQuery()
{
    QString NO,workNumber;
    NO=ui->tableView->model()->index(selectCurrentRow,0).data().toString();
    workNumber=ui->tableView->model()->index(selectCurrentRow,12).data().toString();
    CheckHistoryDialog c(nullptr,NO,workNumber);
    c.exec();
}

void Page0::slot_repairHistoryQuery()
{
    QString NO,workNumber;
    NO=ui->tableView->model()->index(selectCurrentRow,0).data().toString();
    workNumber=ui->tableView->model()->index(selectCurrentRow,2).data().toString();
    RepairHistoryDialog r(nullptr,NO,workNumber);
    r.exec();
}

void Page0::slot_repairApply()
{
    QString NO,workNumber;
    NO=ui->tableView->model()->index(selectCurrentRow,0).data().toString();
    workNumber=ui->tableView->model()->index(selectCurrentRow,2).data().toString();
    RepairDialog r(nullptr,NO,workNumber);
    r.exec();
    on_pushButton_3_clicked();
}

void Page0::initTabText(){
    initTab_2();
    initTab_3();
    initTab_4();
    int checkItems=checkMap.size();
    int recheckItems=recheckMap.size();
    int maintainItems=maintainMap.size();
    if(noticeFlag==0 || (checkItems==0 && recheckItems==0 && maintainItems==0)){
        ++noticeFlag;
    }else{
        ++noticeFlag;
        showNoticeDialog(checkItems,recheckItems,maintainItems);
    }
}

void Page0::showNoticeDialog(int checkItems,int recheckItems,int maintainItems)
{
    QStringList tmpList;
    tmpList<<QString("待点检设备（%1）").arg(checkItems)<<QString("待校验设备（%1）").arg(recheckItems)<<QString("待保养设备（%1）").arg(maintainItems);
    RDesktopTip::setMode(RDesktopTip::AllAnimation);
    RDesktopTip::keepTip(tmpList);
}

void Page0::initTab_2(){
    checkMap=Mes::getInstance()->getItemMap("点检");
    ui->tabWidget->setTabText(1,QString("待点检设备（%1）").arg(checkMap.size()));
    initCheckTreeWidget();
    ui->checkTreeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->checkTreeWidget->expandAll();
}

void Page0::initTab_3(){
    recheckMap=Mes::getInstance()->getItemMap("校验");
    ui->tabWidget->setTabText(2,QString("待校验设备（%1）").arg(recheckMap.size()));
    initRecheckTreeWidget();
    ui->recheckTreeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->recheckTreeWidget->expandAll();
}

void Page0::initTab_4(){
    maintainMap=Mes::getInstance()->getItemMap("保养");
    ui->tabWidget->setTabText(3,QString("待保养设备（%1）").arg(maintainMap.size()));
    initMaintainTreeWidget();
    ui->maintainTreeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->maintainTreeWidget->expandAll();
}

void Page0::initCheckTreeWidget(){
    ui->checkTreeWidget->clear();
    for(auto i=checkMap.begin();i!=checkMap.end();++i){
        QTreeWidgetItem *topItem=new QTreeWidgetItem;
        topItem->setText(0,i.key());
        ui->checkTreeWidget->insertTopLevelItem(ui->checkTreeWidget->topLevelItemCount(),topItem);
        for(auto j=i.value().begin();j!=i.value().end();++j){
            QTreeWidgetItem *subItem=new QTreeWidgetItem;
            subItem->setText(1,j->value(0).toString());
            topItem->addChild(subItem);
            QComboBox *comboBox=new QComboBox;
            QStringList tmpList{"正常","异常"};
            comboBox->addItems(tmpList);
            ui->checkTreeWidget->setItemWidget(subItem,3,comboBox);
            if(j->value(1).toBool()) ui->checkTreeWidget->setItemWidget(subItem,2,new QLineEdit);
        }
    }
}

void Page0::initRecheckTreeWidget(){
    ui->recheckTreeWidget->clear();
    for(auto i=recheckMap.begin();i!=recheckMap.end();++i){
        QTreeWidgetItem *topItem=new QTreeWidgetItem;
        topItem->setText(0,i.key());
        ui->recheckTreeWidget->insertTopLevelItem(ui->recheckTreeWidget->topLevelItemCount(),topItem);
        for(auto j=i.value().begin();j!=i.value().end();++j){
            QTreeWidgetItem *subItem=new QTreeWidgetItem;
            subItem->setText(1,j->value(0).toString());
            topItem->addChild(subItem);
            QComboBox *comboBox=new QComboBox;
            QStringList tmpList{"正常","异常"};
            comboBox->addItems(tmpList);
            ui->recheckTreeWidget->setItemWidget(subItem,3,comboBox);
            if(j->value(1).toBool()) ui->recheckTreeWidget->setItemWidget(subItem,2,new QLineEdit);
        }
    }
}

void Page0::initMaintainTreeWidget(){
    ui->maintainTreeWidget->clear();
    for(auto i=maintainMap.begin();i!=maintainMap.end();++i){
        QTreeWidgetItem *topItem=new QTreeWidgetItem;
        topItem->setText(0,i.key());
        ui->maintainTreeWidget->insertTopLevelItem(ui->maintainTreeWidget->topLevelItemCount(),topItem);
        for(auto j=i.value().begin();j!=i.value().end();++j){
            QTreeWidgetItem *subItem=new QTreeWidgetItem;
            subItem->setText(1,j->value(0).toString());
            topItem->addChild(subItem);
            QComboBox *comboBox=new QComboBox;
            QStringList tmpList{"正常","异常"};
            comboBox->addItems(tmpList);
            ui->maintainTreeWidget->setItemWidget(subItem,3,comboBox);
            if(j->value(1).toBool()) ui->maintainTreeWidget->setItemWidget(subItem,2,new QLineEdit);
        }
    }
}

Page0::~Page0()
{
    delete ui;
}

void Page0::initTableView(QStringList sqlist)
{
    MydeviceTable *model=new MydeviceTable(this);
    model->setSqlist(sqlist);

    model->setTable("userForm");
//    model->setHeaderData(0,Qt::Horizontal,QString("设备编号"));
//    model->setHeaderData(1,Qt::Horizontal,QString("设备名称"));
//    model->setHeaderData(2,Qt::Horizontal,QString("保管人工号"));
//    model->setHeaderData(3,Qt::Horizontal,QString("拥有数量"));
//    model->setHeaderData(4,Qt::Horizontal,QString("超期年限"));
//    model->setHeaderData(5,Qt::Horizontal,QString("经办人工号"));
//    model->setHeaderData(6,Qt::Horizontal,QString("领用时间"));
//    model->setHeaderData(7,Qt::Horizontal,QString("存放地点"));
//    model->setHeaderData(8,Qt::Horizontal,QString("设备状态"));
//    model->setHeaderData(9,Qt::Horizontal,QString("检验时间"));
//    model->setHeaderData(10,Qt::Horizontal,QString("检验周期"));
//    model->setHeaderData(11,Qt::Horizontal,QString("检验项目"));
//    model->setHeaderData(12,Qt::Horizontal,QString("检验人工号"));
    model->select();
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
}

MydeviceTable::MydeviceTable(QObject *parent, QSqlDatabase db)
{

}

QVariant MydeviceTable::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role==Qt::DisplayRole && orientation==Qt::Horizontal){
        return labels[section];
    }
    return QAbstractTableModel::headerData(section,orientation,role);
}

QString MydeviceTable::selectStatement() const
{
    QString condition=QString("on a.NO=b.NO and a.useWorkNumber='%1' and a.useAccount!=0").arg(Mes::getInstance()->workNumber);
    for(QString tmp:sqlist){
        if(tmp==NULL){
            continue;
        }
        condition+=QString(" and ")+tmp;
    }

    QString sql=QString("SELECT a.[NO],b.[norms] \
                        ,a.[useWorkNumber]  \
                        ,a.[useAccount] \
                        ,a.[overTime]   \
                        ,a.[agent]  \
                        ,a.[date]   \
                        ,a.[station]    \
                        ,a.[threeModel] \
                        ,a.[noticeTime] \
                        ,a.[cycle]  \
                        ,a.[items],a.[checkWorkNumber]  \
                    FROM [dm-data].[dbo].[userForm] as a inner join [dm-data].[dbo].[importForm] as b %1").arg(condition);
//                        ,a.[checkWorkNumber]
    return sql;
}

void Page0::on_pushButton_2_clicked()       // 查询
{
    QStringList sqlist;
    if(ui->statusCombox->currentText().trimmed()!=""){
        sqlist<<QString("a.threeModel='%1'").arg(ui->statusCombox->currentText().trimmed());
    }

//    if(ui->statusComboBox->currentText().trimmed()!=""){
//        sqlist<<ui->statusComboBox->currentText().trimmed();
//    }

    if(ui->checkWorkNumber->text().trimmed()!=""){
        sqlist<<QString("b.norms like '%%1%'").arg(ui->checkWorkNumber->text().trimmed());
    }

    if(ui->NO->text().trimmed()!=""){
        sqlist<<QString("a.NO like '%%1%'").arg(ui->NO->text().trimmed());
    }

    initTableView(sqlist);
}

void Page0::on_pushButton_3_clicked()       // 刷新
{
    initTableView(QStringList());
}

void Page0::on_pushButton_clicked()         // 导出Excel
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView->model()->rowCount();
        int columns = ui->tableView->model()->columnCount();
        for(int j=0;j<columns;j++){
            textData+=ui->tableView->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                if(j==11){
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString().replace(",",";");
                    textData += "," ;     // for .csv file format
                }else{
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString();
                    textData += "," ;     // for .csv file format
                }
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void Page0::on_tabWidget_currentChanged(int index)
{
    switch (index) {
    case 0: initTableView(QStringList());break;
    case 1: initTab_2();break;
    case 2: initTab_3();break;
    case 3: initTab_4();break;
    }
}


void Page0::on_checkButton_clicked()
{
    QRegExp rx("\\((\\w+)\\)");
    QMap<QString,QList<QList<QVariant>>> submitMap;
    int statusFlag=0;
    int size=ui->checkTreeWidget->topLevelItemCount();
    QTreeWidgetItem *child;
    for(int i=0;i<size;++i){
        child=ui->checkTreeWidget->topLevelItem(i);
        int childCount=child->childCount();
        rx.indexIn(child->text(0));
        QString NO=rx.cap(1);
        QList<QList<QVariant>> dataList;
        for(int j=0;j<childCount;++j){
            QTreeWidgetItem *grandson=child->child(j);
            QList<QVariant> columnList;
            QLineEdit* tmpLine=qobject_cast<QLineEdit *>(ui->checkTreeWidget->itemWidget(grandson,2));
            if(tmpLine!=nullptr){
                if(tmpLine->text().trimmed()==""){
                    QMessageBox::warning(this, QString("提示"), QString("设备状态值不能为空      "));
                    return;
                }else{
                    columnList.push_back(tmpLine->text().trimmed());
                }
            }else{
                columnList.push_back("未填");
            }
            QComboBox* tmpCombox=qobject_cast<QComboBox *>(ui->checkTreeWidget->itemWidget(grandson,3));
            statusFlag+=tmpCombox->currentIndex();
            columnList.push_back(tmpCombox->currentText());
            dataList.push_back(columnList);
        }
        submitMap.insert(NO,dataList);
    }

    if(statusFlag>0){
        QMessageBox box(QMessageBox::Warning,"提示","提交的设备中，含有异常设备，\n\n是否提交？");
        box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        box.setButtonText (QMessageBox::Ok,QString("是"));
        box.setButtonText (QMessageBox::Cancel,QString("否"));
        if(box.exec()==QMessageBox::Cancel){
            return;
        };
    }

    if(!Mes::getInstance()->insertCheckRecord(submitMap,statusFlag>0?"异常":"正常","点检")){
        return;
    }

    initTab_2();
}

void Page0::on_recheckButton_clicked()
{
    QRegExp rx("\\((\\w+)\\)");
    QMap<QString,QList<QList<QVariant>>> submitMap;
    int statusFlag=0;
    int size=ui->recheckTreeWidget->topLevelItemCount();
    QTreeWidgetItem *child;
    for(int i=0;i<size;++i){
        child=ui->recheckTreeWidget->topLevelItem(i);
        int childCount=child->childCount();
        rx.indexIn(child->text(0));
        QString NO=rx.cap(1);
        QList<QList<QVariant>> dataList;
        for(int j=0;j<childCount;++j){
            QTreeWidgetItem *grandson=child->child(j);
            QList<QVariant> columnList;
            QLineEdit* tmpLine=qobject_cast<QLineEdit *>(ui->recheckTreeWidget->itemWidget(grandson,2));
            if(tmpLine!=nullptr){
                if(tmpLine->text().trimmed()==""){
                    QMessageBox::warning(this, QString("提示"), QString("设备状态值不能为空      "));
                    return;
                }else{
                    columnList.push_back(tmpLine->text().trimmed());
                }
            }else{
                columnList.push_back("未填");
            }
            QComboBox* tmpCombox=qobject_cast<QComboBox *>(ui->recheckTreeWidget->itemWidget(grandson,3));
            statusFlag+=tmpCombox->currentIndex();
            columnList.push_back(tmpCombox->currentText());
            dataList.push_back(columnList);
        }
        submitMap.insert(NO,dataList);
    }

    if(statusFlag>0){
        QMessageBox box(QMessageBox::Warning,"提示","提交的设备中，含有异常设备，\n\n是否提交？");
        box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        box.setButtonText (QMessageBox::Ok,QString("是"));
        box.setButtonText (QMessageBox::Cancel,QString("否"));
        if(box.exec()==QMessageBox::Cancel){
            return;
        };
    }

    if(!Mes::getInstance()->insertCheckRecord(submitMap,statusFlag>0?"异常":"正常","校验")){
        return;
    }

    initTab_3();
}

void Page0::on_maintainButton_clicked()
{
    QRegExp rx("\\((\\w+)\\)");
    QMap<QString,QList<QList<QVariant>>> submitMap;
    int statusFlag=0;
    int size=ui->maintainTreeWidget->topLevelItemCount();
    QTreeWidgetItem *child;
    for(int i=0;i<size;++i){
        child=ui->maintainTreeWidget->topLevelItem(i);
        int childCount=child->childCount();
        rx.indexIn(child->text(0));
        QString NO=rx.cap(1);
        QList<QList<QVariant>> dataList;
        for(int j=0;j<childCount;++j){
            QTreeWidgetItem *grandson=child->child(j);
            QList<QVariant> columnList;
            QLineEdit* tmpLine=qobject_cast<QLineEdit *>(ui->maintainTreeWidget->itemWidget(grandson,2));
            if(tmpLine!=nullptr){
                if(tmpLine->text().trimmed()==""){
                    QMessageBox::warning(this, QString("提示"), QString("设备状态值不能为空      "));
                    return;
                }else{
                    columnList.push_back(tmpLine->text().trimmed());
                }
            }else{
                columnList.push_back("未填");
            }
            QComboBox* tmpCombox=qobject_cast<QComboBox *>(ui->maintainTreeWidget->itemWidget(grandson,3));
            statusFlag+=tmpCombox->currentIndex();
            columnList.push_back(tmpCombox->currentText());
            dataList.push_back(columnList);
        }
        submitMap.insert(NO,dataList);
    }

    if(statusFlag>0){
        QMessageBox box(QMessageBox::Warning,"提示","提交的设备中，含有异常设备，\n\n是否提交？");
        box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
        box.setButtonText (QMessageBox::Ok,QString("是"));
        box.setButtonText (QMessageBox::Cancel,QString("否"));
        if(box.exec()==QMessageBox::Cancel){
            return;
        };
    }

    if(!Mes::getInstance()->insertCheckRecord(submitMap,statusFlag>0?"异常":"正常","保养")){
        return;
    }

    initTab_4();
}

void Page0::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void Page0::slot_createQRcode()
{
    QStringList tagList;
    for(int i=0;i<8;i++){
        QString tmp=ui->tableView->model()->index(selectCurrentRow,i).data().toString();
        if(i==0)    {tagList<<QString("设备编号：%1").arg(tmp);continue;}
        if(i==1)    {tagList<<QString("设备名称：%1").arg(tmp);continue;}
        if(i==2)    {tagList<<QString("保管人工号：%1").arg(tmp);continue;}
        if(i==3)    {tagList<<QString("拥有数量：%1").arg(tmp);continue;}
        if(i==4)    {tagList<<QString("超期年限：%1个月").arg(tmp);continue;}
        if(i==6)    {tagList<<QString("领用时间：%1").arg(tmp);continue;}
        if(i==7)    {tagList<<QString("存放地点：%1").arg(tmp);continue;}
    }
    SaveQRCode saveDialog(tagList);
    saveDialog.exec();
}

void Page0::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}
